<template>
	<view class="storehouse_publish_layout">
		<uni-forms ref="forms" :model="formData" validate-trigger="submit" err-show-type="toast" class="uni-forms">
			<uni-forms-item label="题库标题：" required label-width="90">
				<textarea placeholder="题库标题" v-model="formData.title" class="title_textarea"></textarea>
			</uni-forms-item>
			<uni-forms-item name="year" label="所属年份：" required label-width="90">
				<view class="year_picker_container">
					<picker mode="date" :value="formData.year" fields="year" @change="bindDateChange"
						class="year_picker_text">
						{{dayjs(formData.year).format('YYYY年')}}
					</picker>
				</view>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="onsubmit_storehouse">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app'

	import dayjs from 'dayjs';

	const forms = ref(null)

	const questionsObj = uniCloud.importObject('questionsObj')

	const formData = ref({
		title: "",
		year: new Date().getTime(),
		type: 0
	})

	onLoad(async (params) => {
		if (params.id) {
			let res = await questionsObj.storehouse_detail_simple(params.id)
			console.log(res);
			if (res.errCode != 0) {
				return
			}
			formData.value = res.data
		} else {
			formData.type = Number(params.type)
		}
	})

	async function onsubmit_storehouse() {
		let res = await questionsObj.storehouse_publish(formData.value)
		if (res.errCode != 0) {
			uni.showToast({
				title: res.errMsg,
				icon: 'none'
			})
			return
		}
		uni.$emit('storehouse_publish')
		// 
		uni.showModal({
			content: '题库发布成功，请选择下一步操作',
			confirmText: '添加题目',
			cancelText: '返回上一级',
			success: (success) => {
				if (success.confirm) {
					uni.redirectTo({
						url: '/pages_lianxi/linianzhenti/topic_publish?question_storehouse_id=' + (
							res.id || formData.value._id)
					})
				} else {
					uni.navigateBack()
				}
			}
		})
	}

	function bindDateChange(e) {
		formData.value.year = new Date(`${e.detail.value}-01-01 00:00:00`).getTime()
	}
</script>

<style lang="scss" scoped>
	.storehouse_publish_layout {
		width: 100%;

		.uni-forms {
			padding: 0 20rpx;
		}

		.title_textarea {
			width: 100%;
			font-size: 28rpx;
			padding: 10rpx;
			border: 1rpx solid rgb(229, 229, 229);
			height: 200rpx;
			border-radius: 4rpx;
		}

		.year_picker_container {
			height: 100%;

			.year_picker_text {
				font-size: 28rpx;
				height: 100%;
				display: flex;
				align-items: center;
				padding: 0 10rpx;
				border: 1rpx solid rgb(229, 229, 229);
				border-radius: 4rpx;
			}
		}

		.uni-button-group {
			width: 100%;
			display: flex;
			justify-content: center;

			.uni-button {
				width: 300rpx;
				font-size: 28rpx;
			}
		}
	}
</style>